package com.yww.leetcode2.linkedlist;

import com.yww.leetcode.common.ListNode;

/**
 * @author yww
 * @description 19. 删除链表的倒数第 N 个结点
 * @since 2024/11/12
 */
public class RemoveNthFromEnd17_05 {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummyHead = new ListNode(-1, null);
        dummyHead.next = head;
        ListNode fast = dummyHead;
        ListNode slow = dummyHead;
        // 快指针先走n+1步
        n++;
        while (n > 0 && fast != null) {
            fast = fast.next;
            n--;
        }
        // 快慢指针同时走，fast走向null时，slow刚好指向删除节点前一个节点
        while (fast != null) {
            fast = fast.next;
            slow = slow.next;
        }
        // 删除节点
        slow.next = slow.next.next;
        return dummyHead.next;
    }
}
